package com.hq.door.controller;

import java.beans.PropertyEditorSupport;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hq.door.bean.OAuth;
import com.hq.door.dto.ImageCode;
import com.hq.door.dto.Pagination;
import com.hq.door.dto.Parent;
import com.hq.door.dto.ParentApplyFront;
import com.hq.door.dto.ParentRecordFront;
import com.hq.door.dto.StudentInfo;
import com.hq.door.pojo.TClass;
import com.hq.door.pojo.TParent;
import com.hq.door.pojo.TStudent;
import com.hq.door.service.IParentService;
import com.hq.door.util.HttpClientUtil;
import com.hq.door.util.JacksonUtil;
import com.hq.door.util.staticErrorCode;

@Controller
@RequestMapping("/front/parent")
@CrossOrigin(origins = { "*" }, allowedHeaders = { "Access-Control" })
public class ParentFrontController {
	/*
	 * http://127.0.0.1:8080/huaqiao/front/parent/apply?pageNo=1&pageSize=10&type
	 * =0
	 * http://127.0.0.1:8080/huaqiao/front/parent/record?pageNo=1&pageSize=10&
	 * type=1
	 * http://127.0.0.1:8080/huaqiao/front/parent/login?userName=&password
	 * =&code= http://127.0.0.1:8080/huaqiao/front/parent/imageCode
	 */
	@Autowired
	IParentService parentService;

	/**
	 * 查询班级信息列表
	 * @param grade	年级
	 * @return
	 */
	@RequestMapping("/queryClazzList")
	@ResponseBody
	public Object queryClazzList(@RequestParam String grade) {
		Map<String,Object> result = new HashMap<>();
		List<TClass> clazzList = parentService.queryClazzList(grade);
		if(clazzList==null||clazzList.size()<=0){
			result.put("code", "001");
			result.put("obj", null);
			result.put("tip", "无查询结果");
		}else{
			result.put("code", "000");
			result.put("obj", clazzList);
			result.put("tip", "该年级下还没有班级哦");
		}
		return result;
	}
	
	/**
	 * 查询学生信息列表
	 * @param clazzName	班级名称
	 * @return
	 */
	@RequestMapping("/queryStudentList")
	@ResponseBody
	public Object queryStudentList(@RequestParam String clazzName) {
		Map<String,Object> result = new HashMap<>();
		List<TStudent> studentList = parentService.queryStudentList(clazzName);
		if(studentList==null||studentList.size()<=0){
			result.put("code", "001");
			result.put("obj", null);
			result.put("tip", "无查询结果");
		}else{
			result.put("code", "000");
			result.put("obj", studentList);
			result.put("tip", "该班级下没有学生信息");
		}
		return result;
	}
	
	/**
	 * 家长申请绑定学生
	 * @param parentName
	 * @param phoneNum
	 * @param studentName
	 * @param clazz
	 * @param reason
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/weChatBind")
	@ResponseBody
	public Object weChatBind(@RequestParam String parentName, 
							 @RequestParam String phoneNum,
							 @RequestParam String studentCode,
							 @RequestParam String clazz,
							 @RequestParam String reason) throws Exception {
		Map<String,Object> result = new HashMap<>();
		TParent parent = parentService.wxBind(parentName, phoneNum, studentCode, clazz, reason);
		if(parent!=null){
			result.put("code", "000");
			result.put("obj", null);
			result.put("tip", "正在申请中");
		}else{
			result.put("code", "001");
			result.put("obj", null);
			result.put("tip", "没有您所要绑定的学生信息");
		}
		return result;
	}
	
	
	/**
	 * 家长微信登录
	 * 
	 * @param session
	 * @param wexinId
	 * @return
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws
	 */
	@RequestMapping("/weChatLogin")
	@ResponseBody
	public Object weChatLogin(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		// 家长端 登录页面触发
		String mobile = request.getParameter("telNum");
		String verifyCode = request.getParameter("verifyCode");
		System.out.println("telNum:" + mobile + ",verifyCode:" + verifyCode);
		if ("1234".equals(verifyCode)) {
			String weixinId = (String) session.getAttribute("weixinId");
			TParent tparent = parentService.modifyParent(mobile, weixinId);
			if (tparent != null) {
				session.setAttribute("loginUser", tparent);
				return staticErrorCode.error_code_success;
			} else {
				return staticErrorCode.error_code_mismatch_wxBind_fail;
			}
		} else {
			return staticErrorCode.error_code_mismatch_verifyCode;
		}
	}

	// ------------------------------------------------------------------------------------
	/**
	 * 分页带参查询家长对应的学生刷卡记录信息
	 * 
	 * @param pib
	 * @return
	 */
	@RequestMapping(value = "/record", method = RequestMethod.POST)
	@ResponseBody
	public Pagination findStuInfosByRecord(HttpSession session,
			ParentRecordFront prf) {
		TParent tparent = (TParent) session.getAttribute("loginUser");
		Pagination pagination = parentService
				.queryRecordsByParent(tparent, prf);
		if (pagination == null) {
			pagination = new Pagination(0, "", null);
		}
		return pagination;
	}

	/**
	 * 分页带参查询家长对应的学生外出申请记录信息
	 * 
	 * @param pib
	 * @return
	 */
	@RequestMapping(value = "/apply", method = RequestMethod.POST)
	@ResponseBody
	public Pagination findStuInfosOfApply(HttpSession session,
			ParentApplyFront paf) {
		TParent tparent = (TParent) session.getAttribute("loginUser");
		Pagination pagination = parentService.queryApplysByParent(tparent, paf);
		if (pagination == null) {
			pagination = new Pagination(0, "", null);
		}
		return pagination;
	}

	@RequestMapping("/getCurStu")
	@ResponseBody
	public Object getCurStu(HttpSession session) {
		TParent tparent = (TParent) session.getAttribute("loginUser");
		TStudent tStudent = null;
		StudentInfo studentInfo = new StudentInfo();
		if (tparent.getTStudent() != null) {
			tStudent = tparent.getTStudent();
			studentInfo.setName(tStudent.getName());
			if (tStudent.getTClass() != null) {
				studentInfo.setClassname(tStudent.getTClass().getName());
			}
		}
		return studentInfo;
	}

	// ------------------------------------------------------------------------------------
	/**
	 * 用户退出
	 * 
	 * @param session
	 */
	@RequestMapping("/exit")
	@ResponseBody
	public void exit(HttpSession session) {
		session.removeAttribute("loginUser");
	}

	/**
	 * 生成前台登录页面验证码
	 * 
	 * @param parent
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/imageCode")
	public void getImageCode(HttpServletRequest request,
			HttpServletResponse response, ImageCode imageCode)
			throws IOException {
		String clientId = request.getRequestedSessionId();
		// 禁止图片缓存
		response.setHeader("Progma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 表明生成的响应是图片
		response.setContentType("image/jpeg");
		// 将图像输出到OutputStream流中
		OutputStream outputStream = response.getOutputStream();
		imageCode.setSessionKey("ImageCode" + clientId);
		ImageIO.write(imageCode.getImage(request), "jpeg", outputStream);
		// 关闭流
		outputStream.close();
	}

	/**
	 * 家长端登录
	 * 
	 * @param parent
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	@ResponseBody
	public Object check(HttpSession session, Parent parent) {
		String clientId = session.getId();
		String baseCode = (String) session.getAttribute("ImageCode" + clientId);
		if (baseCode == null || !baseCode.equalsIgnoreCase(parent.getCode())) {// 忽略大小写
			return staticErrorCode.error_code_mismatch_verifyCode;
		}
		TParent tparent = parentService.check(parent);
		if (tparent != null) {
			session.setAttribute("loginUser", tparent);
			return staticErrorCode.error_code_success;
		} else {
			return staticErrorCode.error_code_mismatch_user_or_password;
		}
	}

	// @RequestMapping("/weChatCheck")
	// public String weChatCheck(HttpServletRequest request) throws Exception{
	// HttpSession session = request.getSession();
	// String state =request.getParameter("state");
	// String forwardURL = "/front_end/weChat/login_weChat";
	// if(null!=request.getParameter("state")&&"parent".equals(request.getParameter("state")))
	// {//家长端 微信链接触发
	// String code = request.getParameter("code");
	// OAuth oa = getOAuth(null, code);
	// String weixinId = oa.getOpenid();
	// if(null!=weixinId&&!"".equals(weixinId))
	// {
	// session.setAttribute("weixinId", weixinId);
	// TParent tparent = parentService.wxLogin(weixinId);
	// if(tparent!=null)
	// {
	// session.setAttribute("loginUser", tparent);
	// forwardURL = "/front_end/weChat/patriarch/card_weChat_parent";
	// return forwardURL;
	// }
	// else
	// {
	// return forwardURL;
	// }
	// }
	// else
	// {
	// return forwardURL;
	// }
	// }
	// return forwardURL;
	// }

	// @RequestMapping("/weChatCheck")
	// public String weChatCheck(HttpSession session){
	// String weixinId = (String) session.getAttribute("weixinId");
	// if(weixinId!=null){
	// TParent tparent = parentService.wxLogin(weixinId);
	// if(tparent!=null){
	// session.setAttribute("loginUser", tparent);
	// return "/front_end/weChat/patriarch/card_weChat_parent";
	// }else{
	// return "/front_end/weChat/login_weChat";
	// }
	// }
	// return null;
	// }

	@RequestMapping("/weChatCheck")
	public String weChatCheck(HttpSession session) throws Exception {
		String forwardURL = "/front_end/weChat/login_weChat";
		// 家长端 微信链接触发

		String weixinId = (String) session.getAttribute("wexinId");
		if (null != weixinId && !"".equals(weixinId)) {
			TParent tparent = parentService.wxLogin(weixinId);
			if (tparent != null) {
				session.setAttribute("loginUser", tparent);
				forwardURL = "/front_end/weChat/patriarch/card_weChat_parent";
				return forwardURL;
			} else {
				return forwardURL;
			}
		} else {
			return forwardURL;
		}

	}

	// ------------------------------------------------------------------------------------
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// 日期处理
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		df.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
		binder.registerCustomEditor(Timestamp.class,
				new PropertyEditorSupport() {
					@Override
					public void setAsText(String value) {
						setValue(new Timestamp(Long.valueOf(value)));
					}
				});
	}

	// ------------------------------------------------------------------------------------
	public OAuth getOAuth(String path, String code) throws Exception {
		OAuth oa = null;
		System.out.println("获取网页授权凭据");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx546829eea71a10db&secret=601cbb8a2cef1cb23ca2b66614fd074b&code="
				+ code + "&grant_type=authorization_code";
		String json = HttpClientUtil.httpGetRequest(url);
		if (json != null && !"".equals(json)) {
			oa = (OAuth) JacksonUtil.json2object(json, OAuth.class);
		}
		return oa;
	}

	// ------------------------------------------------------------------------------------
	/**
	 * 测试使用spmvc 测试使用spmvc
	 * 
	 * @param request
	 * @param parent
	 * @param code
	 * @return
	 */
	@RequestMapping("/parent/getInfo")
	@ResponseBody
	public Parent test(HttpServletRequest request, Parent parent, String code) {
		Parent po = null;// parentService.check(parent);
		System.out.println(po);
		return po;
	}

}
